<template>
  <h1>Todo-List视图</h1>
  <TodoHeader @submit-todo="recevieTodo" />
  <TodoMain :todo-list="todoList"/>
  <TodoFooter :count="todoListShow.length" @filter-todo="handleFilter" />
</template>
<script setup>

  import { ref, computed,watch } from 'vue';
  import TodoFooter from './TodoFooter.vue';
  import TodoHeader from './TodoHeader.vue';
  import TodoMain from './TodoMain.vue';

  const todoList = ref(JSON.parse(localStorage.getItem('qvtu-todo') || '[]') || [])

  const recevieTodo = (newTodoItem) => {
    todoList.value.push(newTodoItem)
  }

  const handleDelete = (index) => {
    todoList.value.splice(index, 1)
  }

  const typeString = ref('all')

  const todoListShow = computed(() => {

    if (typeString.value === 'all') {
      return todoList.value
    }

    return todoList.value.filter(function (item) {
      if (typeString.value === 'not-complete') {
        return !item.completed
      }
      return item.completed
    })
  })
  
  const handleFilter = (type) => {
    typeString.value = type
  }

  watch(todoList,(newValue,oldValue)=>{
    localStorage.setItem('qvtu-tudo',JSON.stringify(newValue))
  },{deep:true})

</script>
